package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.OrderConstant;
import com.atguigu.common.constant.OrderConstantCommon;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.exception.BizException;
import com.atguigu.common.to.SkuInfoTO;
import com.atguigu.common.to.SpuInfoTO;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTO;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVO> confirmVOThreadLocal = new ThreadLocal<>();

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private MemberFeignService memberFeignService;

    @Resource
    private CartFeignService cartFeignService;

    @Resource
    private ThreadPoolExecutor executor;

    @Resource
    private WareFeignService wareFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ProductFeignService productFeignService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private PaymentInfoService paymentInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    public void a(){
        OrderServiceImpl o = (OrderServiceImpl) AopContext.currentProxy();
        o.b();
        o.c();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void b(){

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void c(){

    }

    @Override
    public PageUtils getCurrentUserOrderList(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginInterceptor.loginUser.get();
        // 获取当前登录用户的所有订单
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );
        // 查出每个订单下的订单项
        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.listByOrderSn(order.getOrderSn());
            order.setItems(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(collect);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(AlipayNotifyVO vo) {
        //保存交易流水
        PaymentInfoEntity entity = new PaymentInfoEntity();
        entity.setAlipayTradeNo(vo.getTrade_no());
        entity.setOrderSn(vo.getOut_trade_no());
        entity.setPaymentStatus(vo.getTrade_status());
        entity.setCallbackTime(vo.getNotify_time());
        entity.setTotalAmount(new BigDecimal(vo.getTotal_amount()));
        entity.setSubject(vo.getSubject());

        paymentInfoService.save(entity);
        //修改订单状态
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功
            String outTradeNo = vo.getOut_trade_no();
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setStatus(OrderConstantCommon.OrderStatusEnum.PAYED.getCode());
            this.baseMapper.update(orderEntity, new QueryWrapper<OrderEntity>().eq("order_sn", vo.getOut_trade_no()));
        }
        return "success";
    }

    @Transactional
    @Override
    public boolean createSeckillOrder(SeckillOrderTO seckillOrderTO) {
        // 1.验证令牌，秒杀服务发过来的消息，直接创建订单
        // 2.快速构建订单项，其实应该快速创建出一个最简单的订单并保存，及时返回，用户支付，其他信息异步完善
        OrderItemEntity orderItem = buildSeckillOrderItem(seckillOrderTO);
        // 3.构建订单
        OrderEntity orderEntity = buildSeckillOrder(seckillOrderTO);
        // 4.设置订单需要求和项
        calculateOrder(orderEntity, Arrays.asList(orderItem));
        // 5.后端计算的价格和前端传来的价格进行验证，秒杀后台下单不需要
        // 6.远程锁定库存，秒杀活动的库存上架前已锁定
        // 7.保存订单，保存订单项
        this.save(orderEntity);
        orderItemService.save(orderItem);

        // 8.向mq中发送订单创建完成消息
        try {
            rabbitTemplate.convertAndSend(OrderConstant.ORDER_EVENT_EXCHANGE, OrderConstant.ORDER_CREATE_ROUTING_KEY, orderEntity);
        } catch (AmqpException e) {
            log.warn("向mq发送订单新创建消息失败，自动重试一次");
            rabbitTemplate.convertAndSend(OrderConstant.ORDER_EVENT_EXCHANGE, OrderConstant.ORDER_CREATE_ROUTING_KEY, orderEntity);
        }
        // 9.清空购物车中这些购物项，秒杀业务无需经过购物车，消息队列快速下单
        return true;
    }

    /**
     * 订单中一些属性需要订单项总和的计算
     *
     * @param items
     * @return
     */
    private void calculateOrder(OrderEntity orderEntity, List<OrderItemEntity> items) {
        int growth = 0, integration = 0;
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal couponAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        BigDecimal integrationAmount = new BigDecimal("0");
        if (!CollectionUtils.isEmpty(items)) {
            for (OrderItemEntity item : items) {
                growth += item.getGiftGrowth();
                integration += item.getGiftIntegration();
                totalAmount = totalAmount.add(item.getRealAmount());
                couponAmount = couponAmount.add(item.getCouponAmount());
                promotionAmount = promotionAmount.add(item.getPromotionAmount());
                integrationAmount = integrationAmount.add(item.getIntegrationAmount());
            }
        }
        // 积分和成长值，所有订单项的总和
        orderEntity.setIntegration(integration);
        orderEntity.setGrowth(growth);
        // 总优惠 = 每项优惠了的总和
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setCouponAmount(couponAmount);
        orderEntity.setIntegrationAmount(integrationAmount);
        // 总金额 = 每项应付金额和
        orderEntity.setTotalAmount(totalAmount);
        // 总应付金额 = 总金额+运费
        orderEntity.setPayAmount(totalAmount.add(orderEntity.getFreightAmount()));
    }

    /**
     * 创建秒杀单的完整订单
     *
     * @param seckillOrderTO
     * @return
     */
    private OrderEntity buildSeckillOrder(SeckillOrderTO seckillOrderTO) {
        OrderEntity orderEntity = new OrderEntity();
        // 1.订单创建者
        orderEntity.setMemberId(seckillOrderTO.getMemberId());
        orderEntity.setMemberUsername(seckillOrderTO.getUserName());
        // 2.收货地址和运费
        List<MemberAddressVO> addressVOS = memberFeignService.getAddress(seckillOrderTO.getMemberId());
        addressVOS.forEach(address -> {
            if (address.getDefaultStatus() == 1) {
                orderEntity.setReceiverProvince(address.getProvince());
                orderEntity.setReceiverCity(address.getCity());
                orderEntity.setReceiverDetailAddress(address.getDetailAddress());
                // orderEntity.setReceiverRegion();
                // orderEntity.setReceiverPostCode();
                orderEntity.setReceiverName(address.getName());
                orderEntity.setReceiverPhone(address.getPhone());
                // orderEntity.setReceiveTime();
                // 运费
                orderEntity.setFreightAmount(getSimpleFare(address));
            }
        });

        // 自动确认收货天数
        orderEntity.setAutoConfirmDay(7);
        // 3.支付信息，写死，支付宝
        orderEntity.setPayType(OrderConstant.PayType.ALIPAY.getCode());
        // 4.订单/订单项部分
        orderEntity.setOrderSn(seckillOrderTO.getOrderSn());
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        orderEntity.setStatus(OrderConstant.OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setDeleteStatus(0);
        orderEntity.setConfirmStatus(0);
        // 备注
        // orderEntity.setNote();
        // 5.优惠/发票/快递部分
        return orderEntity;
    }

    /**
     * 构建秒杀单的订单项
     *
     * @param seckillOrderTO
     * @return
     */
    private OrderItemEntity buildSeckillOrderItem(SeckillOrderTO seckillOrderTO) {

        Long skuId = seckillOrderTO.getSkuId();

        // 1.秒杀价格、数量信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTO.getOrderSn());
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuPrice(seckillOrderTO.getSeckillPrice());
        orderItemEntity.setSkuQuantity(seckillOrderTO.getCount());
        BigDecimal zero = new BigDecimal("0");
        // 各种优惠，简略为0
        orderItemEntity.setCouponAmount(zero);
        orderItemEntity.setIntegrationAmount(zero);
        orderItemEntity.setPromotionAmount(zero);
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        // 原价 数量 * 单价
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getIntegrationAmount()).subtract(orderItemEntity.getPromotionAmount());
        // 实际价格=原价-优惠
        orderItemEntity.setRealAmount(subtract);

        // 2.商品基本信息，使用线程池异步编排提高效率
        CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
            // 调用远程服务查询sku详情
            R res = productFeignService.getSkuInfo(skuId);
            if (res.getCode() != 0) {
                log.error("远程调用gulimall-product查询skuinfo失败");
                throw new BizException(BizCodeEnum.CALL_FEIGN_SERVICE_FAILED, "加入购物车失败");
            }
            SkuInfoTO skuInfo = res.getData("skuInfo", SkuInfoTO.class);
            orderItemEntity.setSkuName(skuInfo.getSkuName());
            orderItemEntity.setSkuPic(skuInfo.getSkuDefaultImg());
        }, executor);

        // 3.商品销售属性信息
        CompletableFuture<Void> saleAttrTask = CompletableFuture.runAsync(() -> {
            // 调用远程服务查询sku saleattrs
            List<String> r = productFeignService.getSaleAttrStringList(skuId);
            if (CollectionUtils.isEmpty(r)) {
                log.error("远程调用gulimall-product查询sku saleattr失败");
                throw new BizException(BizCodeEnum.CALL_FEIGN_SERVICE_FAILED);
            } else {
                orderItemEntity.setSkuAttrsVals(r.stream().collect(Collectors.joining(";")));
            }
        }, executor);

        // 4. 商品spu信息部分
        CompletableFuture<Void> spuInfoTask = CompletableFuture.runAsync(() -> {
            R r = productFeignService.getSpuBySkuId(skuId);
            if (r.getCode() != 0) {
                log.error("gulimall-order调用gulimall-product查询spuinfo失败");
                throw new BizException(BizCodeEnum.CALL_FEIGN_SERVICE_FAILED, "秒杀订单创建失败");
            }
            SpuInfoTO spuInfoTO = r.getData(SpuInfoTO.class);
            orderItemEntity.setSpuId(spuInfoTO.getId());
            orderItemEntity.setSpuName(spuInfoTO.getSpuName());
            // orderItemVO.setSpuPic;
            orderItemEntity.setSpuBrand(spuInfoTO.getBrandName());
            orderItemEntity.setCategoryId(spuInfoTO.getCatelogId());

            // 5.所得积分部分
            orderItemEntity.setGiftGrowth(spuInfoTO.getGrowBounds().intValue() * orderItemEntity.getSkuQuantity());
            orderItemEntity.setGiftIntegration(spuInfoTO.getIntegration().intValue() * orderItemEntity.getSkuQuantity());
        }, executor);

        // 等待异步任务执行完成
        try {
            CompletableFuture.allOf(skuInfoTask, saleAttrTask, spuInfoTask).get();
            return orderItemEntity;
        } catch (Exception e) {
            log.error("线程池异步编排构造购物项详细信息失败");
            throw new BizException(BizCodeEnum.THREAD_POOL_TASK_FAILED, "秒杀订单创建失败");
        }
    }

    @Override
    public OrderConfirmVO confirmOrder() {
        OrderConfirmVO vo = new OrderConfirmVO();
        MemberRespVo memberRespVo = LoginInterceptor.loginUser.get();
        System.out.println("主线程：" + Thread.currentThread().getId());
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            System.out.println("memberFuture线程：" + Thread.currentThread().getId());
            //1、远程查询所有的收获地址列表
            List<MemberAddressVO> addressVOS = memberFeignService.getAddress(memberRespVo.getId());
            vo.setAddresses(addressVOS);
        }, executor);

        CompletableFuture<Void> orderFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            System.out.println("orderFuture线程：" + Thread.currentThread().getId());
            //2、远程查询购物车所有选中的选项
            List<OrderSkuVO> orderSkuVOS = cartFeignService.getCurrentUserCartItems();
            vo.setItems(orderSkuVOS);
        }, executor).thenRunAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderSkuVO> items = vo.getItems();
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.getSkuHasStock(skuIds);
            if (r.getCode() != 0) {
                log.error("调用gulimall-ware查询商品库存失败：{}");
                //throw new BizException(BizCodeEnum.CALL_FEIGN_SERVICE_FAILED, "查询库存失败");
            }
            List<SkuStockVo> stockTOList = r.getData(new TypeReference<List<SkuStockVo>>() {
            });
            Map<Long, Long> collect = stockTOList.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
            vo.getItems().forEach(item -> item.setStock(collect.getOrDefault(item.getSkuId(), 0L)));
        }, executor);


        try {
            CompletableFuture.allOf(memberFuture, orderFuture).get();
            //3、查询用户积分
            Integer integration = memberRespVo.getIntegration();
            vo.setIntegration(integration);

            //4、其他数据自动计算

            //5、TODO 防重令牌
            String token = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX + memberRespVo.getId(), token);
            vo.setToken(token);

            return vo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public FareInfoTO getFare(Long addrId) {
        R r = memberFeignService.getAddressId(addrId);
        if (r.getCode() != 0) {
            log.error("调用gulimall-member服务查询地址信息失败");
            //throw new BizException(BizCodeEnum.CALL_FEIGN_SERVICE_FAILED);
        }
        MemberAddressVO address = r.getData("data", MemberAddressVO.class);
        FareInfoTO fareInfoTO = new FareInfoTO();
        fareInfoTO.setAddress(address);
        fareInfoTO.setFare(getSimpleFare(address));
        return fareInfoTO;
    }

    //@GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderVo submitOrder(OrderSubmitVO vo) {
        SubmitOrderVo submitOrderVo = new SubmitOrderVo();
        MemberRespVo loginUser = LoginInterceptor.loginUser.get();
        confirmVOThreadLocal.set(vo);
        //下单：创建订单、验证令牌、验价格、锁库存

        // TODO 1、验证令牌【令牌的对比和删除必须保证原子行】
        //0令牌失败 1删除成功
        String orderToken = vo.getOrderToken();
        String key = OrderConstant.ORDER_TOKEN_PREFIX + loginUser.getId();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long res = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(key), orderToken);
        if (res == 0) {
            log.warn("订单令牌校验失败，已创建或已过期，请重新下单");
            submitOrderVo.setCode(1L);
            return submitOrderVo;
            //throw new BizException(BizCodeEnum.ORDER_HAS_EXPIRED);
        }
        // TODO 2.构建订单
        OrderCreateVO orderCreateVO = createOrder();
        //验价
        BigDecimal payAmount = orderCreateVO.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getTotalPrice();
        if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
            //保存订单
            saveOrder(orderCreateVO);

            //库存锁定,只要有异常，回滚数据
            WareSkuLockVo lockVo = new WareSkuLockVo();
            lockVo.setOrderSn(orderCreateVO.getOrder().getOrderSn());
            List<OrderLockVo> locks = orderCreateVO.getItems().stream().map(item -> {
                OrderLockVo skuVO = new OrderLockVo();
                skuVO.setSkuId(item.getSkuId());
                skuVO.setCount(item.getSkuQuantity());
                skuVO.setSkuTitle(item.getSkuName());
                return skuVO;
            }).collect(Collectors.toList());
            lockVo.setLocks(locks);
            //远程锁库存
            R r = wareFeignService.orderLockStock(lockVo);
            if (r.getCode() == 0) {
                //锁成功了
                submitOrderVo.setCode(0L);
                submitOrderVo.setOrder(orderCreateVO.getOrder());
                //TODO 订单创建成功，发送消息
                rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderCreateVO.getOrder());
                return submitOrderVo;
            } else {
                //锁定失败
                submitOrderVo.setCode(3L);
                return submitOrderVo;
            }
        } else {
            submitOrderVo.setCode(2L);
            return submitOrderVo;
        }
    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        OrderEntity orderEntity = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询当前订单的最新状态
        OrderEntity entity = this.getById(orderEntity.getId());
        OrderTo orderTo = new OrderTo();
        BeanUtils.copyProperties(entity, orderTo);
        if (entity.getStatus() == OrderConstantCommon.OrderStatusEnum.CREATE_NEW.getCode()) {
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderConstantCommon.OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    @Override
    public AlipayVO OrderPay(String orderSn) {
        AlipayVO vo = new AlipayVO();
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        vo.setOutTradeNo(orderSn);
        BigDecimal totalAmount = orderEntity.getTotalAmount().setScale(2, RoundingMode.UP);
        vo.setTotalAmount(totalAmount.toString());
        vo.setSubject("商城购物车支付");
        vo.setBody(orderEntity.getMemberUsername());
        return vo;
    }


    /**
     * 保存订单数据
     *
     * @param orderCreateVO
     */
    private void saveOrder(OrderCreateVO orderCreateVO) {
        //保存订单
        OrderEntity orderEntity = orderCreateVO.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        //保存订单项
        List<OrderItemEntity> orderItems = orderCreateVO.getItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateVO createOrder() {
        OrderCreateVO orderCreateVO = new OrderCreateVO();
        MemberRespVo respVo = LoginInterceptor.loginUser.get();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();

        //2、创建订单号
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(respVo.getId());

        //3、设置运费信息
        OrderSubmitVO vo = confirmVOThreadLocal.get();
        FareInfoTO fareInfoTO = getFare(vo.getAddressId());
        entity.setFreightAmount(fareInfoTO.getFare());

        //4、设置收获人信息
        entity.setReceiverCity(fareInfoTO.getAddress().getCity());
        entity.setReceiverDetailAddress(fareInfoTO.getAddress().getDetailAddress());
        entity.setReceiverName(fareInfoTO.getAddress().getName());
        entity.setReceiverPhone(fareInfoTO.getAddress().getPhone());
        ;
        entity.setReceiverPostCode(fareInfoTO.getAddress().getPostCode());
        entity.setReceiverProvince(fareInfoTO.getAddress().getProvince());
        entity.setReceiverRegion(fareInfoTO.getAddress().getRegion());
        //设置订单相关状态
        entity.setStatus(OrderConstantCommon.OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        //5、获取到所有的订单项
        List<OrderSkuVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> collect = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            orderCreateVO.setItems(collect);
        }

        //6、验价
        computePrice(entity, orderCreateVO.getItems());
        orderCreateVO.setOrder(entity);

        return orderCreateVO;

    }

    private void computePrice(OrderEntity entity, List<OrderItemEntity> items) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额，叠加每一个订单的总额信息
        for (OrderItemEntity order : items) {
            total = total.add(order.getRealAmount());
            coupon = coupon.add(order.getCouponAmount());
            integration = integration.add(order.getIntegrationAmount());
            promotion = promotion.add(order.getPromotionAmount());
            gift = gift.add(new BigDecimal(order.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(order.getGiftGrowth().toString()));
        }
        //订单价格相关
        entity.setTotalAmount(total);
        entity.setPayAmount(total.add(entity.getFreightAmount()));
        entity.setPromotionAmount(promotion);
        entity.setIntegrationAmount(integration);
        entity.setCouponAmount(coupon);
        //设置积分信息
        entity.setIntegration(gift.intValue());
        entity.setGrowth(growth.intValue());

        entity.setDeleteStatus(0);//未删除

    }

    /**
     * 构建一个订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderSkuVO cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        //2、商品的SPU信息
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoVo spuInfoVo = r.getData(SpuInfoVo.class);
        itemEntity.setSpuId(spuInfoVo.getId());
        itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        itemEntity.setSpuName(spuInfoVo.getSpuName());
        itemEntity.setCategoryId(spuInfoVo.getCatelogId());
        //3、商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getSkuTitle());
        itemEntity.setSkuPic(cartItem.getSkuImg());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getAttrs(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal sub = orign.subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(sub);

        return itemEntity;
    }

    /**
     * 简单的运费计算
     *
     * @param address
     * @return
     */
    private BigDecimal getSimpleFare(MemberAddressVO address) {
        // 简化运费计算
        if (address != null) {
            String phone = address.getPhone();
            if (!StringUtils.isEmpty(phone)) {
                // 简化计算运费过程
                return new BigDecimal(phone.substring(phone.length() - 1));
            }
        }
        return new BigDecimal("0");
    }

}